import os
import sys
import json
import cv2
from PIL import Image
import numpy as np
import matplotlib.pylab as plt
from imageio import imread

sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))

import yaml
import paddle
from tools.infer.utility import draw_ocr_box_txt


def denormalize(img):
    mean = np.array([0.485, 0.456, 0.406])
    std = np.array([0.229, 0.224, 0.225])

    img = np.transpose(img, (1, 2, 0))
    img = img[:, :, ::-1]
    img = img * std + mean
    img = np.clip(img, 0, 1)    

    return img


def main():
    # label_fname = r"F:\Data\tianchiOCR\labels\example.txt"
    label_fname = r"F:\Data\tianchiOCR\labels\Xeon1OCR_round2_train1_20210816.txt"
    data_dir = r"F:\Data\tianchiOCR\images"
    font_path = r"F:\Github\PaddleOCR-release-2.1\doc\fonts\simfang.ttf"

    annotations = []
    with open(label_fname, 'r', encoding='utf-8') as fh:
        for line in fh.readlines():
            content = line.strip().split('\t')
            img_name = content[0]
            ann = json.loads(content[1])
            annotations.append([img_name, ann])

    # content = annotations[2578]
    for k, content in enumerate(annotations):
        img_fname = os.path.join(data_dir, content[0])
        boxes = []
        texts = []
        flag = False
        for ann in content[1]:
            txt = ann['transcription']
            boxes.append(np.asarray(ann['points']))
            texts.append(ann['transcription'])
            if len(txt) > 0 and txt[0] == '*':
                print(k, txt)
                flag = True

        if flag:
            img = Image.open(img_fname)
            img_show = draw_ocr_box_txt(img, boxes, texts, font_path=font_path)
            plt.imshow(img_show)
            plt.title(k)
            plt.show()




if __name__ == '__main__':
    main()